package com.ysxsoft.wdg.adapter.order;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.umeng.socialize.UMShareAPI;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.cart.ShopcartBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.PinDetailResponse;
import com.ysxsoft.wdg.bean.response.PinOrderResponse;
import com.ysxsoft.wdg.bean.response.ShouResponse;
import com.ysxsoft.wdg.bean.response.StPayResponse;
import com.ysxsoft.wdg.bean.response.WxResponse;
import com.ysxsoft.wdg.bean.zy.ZyOrderDetailBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.KanWebViewActivity;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.ui.activity.my.KanActivity;
import com.ysxsoft.wdg.ui.activity.order.AplyBackOrderActivity;
import com.ysxsoft.wdg.ui.activity.order.EmsActivity;
import com.ysxsoft.wdg.ui.activity.order.PinOrderPlActivity;
import com.ysxsoft.wdg.ui.activity.order.ZyOrderPlActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.SharePopupWindow;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class PinOrderDetailActivity extends BaseActivity  implements PayResultListener {

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_address)
    TextView tvAddressAddress;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_goods_money)
    TextView tvGoodsMoney;
    @BindView(R.id.tv_yun)
    TextView tvYun;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.parent)
    RelativeLayout parent;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.tv_pay_type)
    TextView tvPayType;
    @BindView(R.id.tv_l)
    TextView tv_l;
    @BindView(R.id.tv_r)
    TextView tv_r;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private String phone = "", orderid = "", uid = "";
    private ZyOrderDetailAdapter adapter;
    private SharePopupWindow popupWindow;
    private UMShareAPI mShareAPI;
    private String mobile;

    private boolean isQuickReturned=false;//是否是快速创建的

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pt_order_detail;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("订单详情");

        uid = SharePrefUtils.getUserId();
        orderid = getIntent().getStringExtra("orderid");
        String money = getIntent().getStringExtra("money");
        if(money!=null){
            String type = getIntent().getStringExtra("type");
            String url = getIntent().getStringExtra("url");
            isQuickReturned=true;
//            showPayWindow(money,orderid);
        }

        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        adapter = new ZyOrderDetailAdapter(R.layout.include_order_goods);
        recyclerview.setAdapter(adapter);
//        bean= (PinOrderResponse.DataBean) getIntent().getSerializableExtra("data");
//        fillView(bean);
        mShareAPI = UMShareAPI.get(PinOrderDetailActivity.this);
        popupWindow = new SharePopupWindow(PinOrderDetailActivity.this, mShareAPI);
        PayListenerUtils.getInstance(this).addListener(this);


        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!"".equals(SharePrefUtils.getUserId())){
            getDetail(orderid);
        }else{
            ToastUtils.showToast("请登录！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PayListenerUtils.getInstance(this).removeListener(this);
    }

    /**
     * 填充视图
     */
    private void fillView(PinDetailResponse.DataBean d) {

        //1.订单状态
        int type = 0;
        int subType=0;
        PinDetailResponse.DataBean.OrderBean bean = d.getOrder();

        if (bean.getO_status()==0) {//0未支付   1支付成功
            tvStatus.setText("待付款");
        }else {//支付成功
            if (bean.getIstuan() == 0) {//0拼团中1拼团成功2拼团失败
                type = 1;
                tvStatus.setText("拼团中，还差" + bean.getCa_num() + "人成团");
//                tvStatus.setText("待发货");
            } else if (bean.getIstuan() == 1) {
                type = 2;
                tvStatus.setText("待发货");
                switch (bean.getO_status()){
                    case 2://订单已发货
                        type = 6;
                        tvStatus.setText("待收货");
                        break;
                    case 3://订单已收货
                        type = 7;
                        tvStatus.setText("待评价");
                        break;
                    case 4://订单完成
                        type = 8;
                        tvStatus.setText("订单已完成");
                        break;
                }
            }else if (bean.getIstuan() == 2) {
                type = 3;
            }
        }

        PinDetailResponse.DataBean.DetailBean de=d.getDetail();
        if(de.getStatus()==5){
            tvStatus.setText("退款中");
            type = 5;
        }

        //2.收货人地址
        tvAddressName.setText(d.getAddress().getName());
        tvAddressPhone.setText(d.getAddress().getPhone());
        tvAddressAddress.setText(d.getAddress().getCity() + d.getAddress().getProvince() + d.getAddress().getCounty() + d.getAddress().getAddress());
        //3.填充商品
        PinDetailResponse.DataBean.DetailBean item = d.getDetail();
        List<PinDetailResponse.DataBean.DetailBean> datas = new ArrayList<>();
        datas.add(item);

        adapter.setNewData(datas);//填充商品
        //4.商品金额
        tvGoodsMoney.setText("￥" + bean.getAccount());
        //5.运费
        tvYun.setText("￥" + bean.getYun());
        //6.订单总价
        tvTotalMoney.setText("￥" + bean.getAccount());
        //7.联系商家
        mobile=d.getMobile();
        //8.订单详情
        tvOrderNo.setText("订单编号：" + bean.getDsn());
        tvOrderTime.setText("订单时间：" + bean.getAddtime());
        tvPayType.setText("支付方式：在线支付");
//        if(orderBean.getPaytype()==0){
//        }else if(orderBean.getPaytype()==1){
//            tvPayType.setText("支付方式：支付宝支付");
//        }else{
//            tvPayType.setText("支付方式：微信支付");
//        }
        if (!"0".equals(bean.getStatus())) {
            tvPayTime.setVisibility(View.VISIBLE);
            tvPayTime.setText("支付时间：" + bean.getPaytime());
        } else {
            tvPayTime.setVisibility(View.GONE);
        }

        //控制按钮
        switch (type) {
            case 0://待付款
                tv_l.setText("取消订单");
                tv_r.setText("立即付款");
                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder(orderid);
                    }
                });
                tv_r.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        showPayWindow(bean.getAccount(), "" + bean.getOrderid());
                    }
                });
                bottom.setVisibility(View.VISIBLE);
                break;
            case 1://拼团中
//                tv_l.setText("退款");
                tv_l.setVisibility(View.GONE);
                tv_r.setText("邀请参团");
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.setShareData(getString(R.string.app_name), UrlHost.BASE_URL+"/index.html#/login?code=" + SharePrefUtils.getUserCode() + "&type=1&build_id=" + bean.getTuanid(), UrlHost.BASE_URL+"/index.html#/login?code=" + SharePrefUtils.getUserCode() + "&type=1&build_id=" + bean.getTuanid(), "", 0);
                        popupWindow.show(parent);
                    }
                });
                bottom.setVisibility(View.VISIBLE);
                break;
            case 2://拼团成功 待发货
                tv_l.setText("退款");
                tv_l.setVisibility(View.GONE);
                tv_r.setText("提醒发货");
                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AplyBackOrderActivity.start(PinOrderDetailActivity.this, bean.getOrderid() + "", 1);//自营满减
                    }
                });
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        notifyOrder(bean.getOrderid() + "");
                    }
                });
                bottom.setVisibility(View.VISIBLE);
                break;
            case 3://拼团失败进不来

                break;
            case 5://隐藏退款
                tv_l.setVisibility(View.GONE);
                tv_r.setVisibility(View.GONE);

//                tv_l.setText("退款中");
////                tv_r.setText("提醒发货");
//                tv_r.setVisibility(View.GONE);
//                tv_l.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                    }
//                });
                break;
            case 6://待收货
                tv_l.setVisibility(View.VISIBLE);
                tv_r.setVisibility(View.VISIBLE);
                tv_l.setText("查看物流");
                tv_l.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //查看物流
                        Intent intent = new Intent(PinOrderDetailActivity.this, EmsActivity.class);
                        intent.putExtra("emsNo", bean.getKd_no());
                        intent.putExtra("emsTypeCode", bean.getKd_type());
                        startActivity(intent);
                    }
                });
                tv_r.setText("确认收货");
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //确认收货
                        shou(orderid);
                    }
                });
                bottom.setVisibility(View.VISIBLE);
                break;
            case 7://待评价
                tv_l.setVisibility(View.GONE);
                tv_r.setVisibility(View.VISIBLE);
                tv_r.setText("立即评价");
                tv_r.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //立即评价
                        PinOrderPlActivity.start(PinOrderDetailActivity.this, d.getDetail().getProductid() + "", bean.getOrderid()+"", 0,true);//评价自营商品
                    }
                });
                bottom.setVisibility(View.VISIBLE);
                break;
            case 8://订单已完成
                tv_l.setVisibility(View.GONE);
                tv_r.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void setListener() {
    }

    /**
     * 确认收货
     */
    private void shou(String orderId) {
        String type = "2";
        OkHttpUtils.post()
                .url(UrlHost.SHOU)
                .addParams("type", type)//自营商城1满减2
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    ShouResponse shouResponse = JsonUtils.parseByGson(response, ShouResponse.class);
                    if (shouResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(shouResponse.getCode())) {
                        ToastUtils.showToast(shouResponse.getMs());
                       getDetail(orderId);
                    } else {
                        ToastUtils.showToast(shouResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    @OnClick({R.id.title_finish, R.id.tv_kf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                if(isQuickReturned){//如果是网页跳转过来的就返回主页
                    MainActivity.start(this);
                }else{
                    finish();
                }
                break;
            case R.id.tv_kf:
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showToast("请稍后再试");
                    return;
                }
                ViewUtils.call(this, mobile);
                break;
        }
    }

    PayPopWindow2 payPopWindow;

    private void showPayWindow(String payMoney, String orderId) {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }
        payPopWindow = new PayPopWindow2(this, payMoney);
        payPopWindow.show(parent);
        payPopWindow.setOnPayLiatener(new PayPopWindow2.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert(PinOrderDetailActivity.this);
                switch (payType) {
                    case 0://余额支付
                        postPayYue(orderId, payMoney);
                        break;
                    case 1://支付宝支付
                        postPayZfb(orderId, payMoney);
                        break;
                    case 2://微信支付
//                        ToastUtils.showToast("暂未开通");
//                        AlertUtils.dismissAlert();
                        postPayWx(orderId, payMoney);
                        break;
                }
            }
        });
    }

    private void postPayWx(String orderId, String payMoney) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", payMoney)//总价格
                .addParams("type", "2")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    WxResponse wxResponse = JsonUtils.parseByGson(response, WxResponse.class);
                    if (wxResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(wxResponse.getCode())) {
                        WxResponse.DataBean dataBean = wxResponse.getData();
                        WxPayBean bean = new WxPayBean();
                        bean.setAppid(dataBean.getAppid());
                        bean.setNoncestr(dataBean.getNoncestr());
                        bean.setPackageX(dataBean.getPackageX());
                        bean.setPartnerid(dataBean.getPartnerid());
                        bean.setPrepayid(dataBean.getPrepayid());
                        bean.setSign(dataBean.getSign());
                        bean.setTimestamp(""+dataBean.getTimestamp());
                        PayUtils.getInstance(mContext).toWxPay(bean);
                    } else {
                        ToastUtils.showToast(wxResponse.getMs());
                    }
                } else {
                }
            }
        });

//        WxPayBean payBean=new WxPayBean();
////        payBean.setAppid();
//        PayUtils.pay(this,1,"",payBean);
    }

    /**
     * 取消订单
     */
    private void cancelOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.CANCEL_TUAN_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                        ListObserverMap.cancel("PinOrderFragment");
                        finish();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 通知发货
     */
    private void notifyOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.NOTIFY_SHOP)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 自营商城余额支付
     */
    private void postPayYue(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "3")// 	1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        ToastUtils.showToast(stPayResponse.getMs());
                        ListObserverMap.pay("PinOrderFragment");
                        finish();
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 自营商城支付宝支付
     */
    private void postPayZfb(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "1")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        PayUtils.getInstance(mContext).pay(PinOrderDetailActivity.this, PayUtils.PAY_TYPE_ALI, stPayResponse.getData(), null);
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    class ZyOrderDetailAdapter extends BaseQuickAdapter<PinDetailResponse.DataBean.DetailBean, BaseViewHolder> {


        public ZyOrderDetailAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, PinDetailResponse.DataBean.DetailBean item) {
            ViewUtils.loadImage(mContext, item.getPic() == null ? "" : item.getPic(), (ImageView) helper.getView(R.id.iv_goods));
            helper.setText(R.id.tv_goods_name, item.getProduct_name());
            helper.setText(R.id.tv_rules, item.getRule_name());
            helper.setText(R.id.tv_money, mContext.getString(R.string.price_rmb, item.getL_price()));
            helper.setText(R.id.tv_num, "x" + item.getNum());
        }
    }

    /**
     * 查询订单详情
     */
    private void getDetail(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.PIN_ORDER_DETAIL)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    PinDetailResponse pinDetailResponse = JsonUtils.parseByGson(response, PinDetailResponse.class);
                    if (pinDetailResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(pinDetailResponse.getCode())) {
                        fillView(pinDetailResponse.getData());
                    } else {
                        ToastUtils.showToast(pinDetailResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功");
        getDetail(orderid);
//        finish();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败");
    }

    @Override
    public void onPayCancel() {
        ToastUtils.showToast("取消支付");
    }

    ///////////////////////////////////////////////////////////////////////////
    //确认收货
    ///////////////////////////////////////////////////////////////////////////

}
